﻿using System.Linq;
using System.Reflection;
using System.Text;
using Properties;

namespace Borg
{
    public class ContractInfo : AssemblyInfo
    {
        internal static int nextId = 1;
        internal RepositoryCollection<SlotDefinition> slotDefinitions;

        internal static QualificationState unqualifiedState =
            QualificationState.None |
            QualificationState.QualificationMissing |
            QualificationState.ContractHasNoSlotDefinitions;

        internal static QualificationState warningState =
            QualificationState.None |
            QualificationState.ContractNameAlreadyExists;

        internal ContractInfo(RepositoryId repositoryId, Assembly assembly)
            : base(repositoryId, assembly)
        {
            id = nextId++;
        }

        internal ContractInfo(RepositoryId repositoryId, Assembly assembly,
            RepositoryCollection<SlotDefinition> slotDefinitions)
            : this(repositoryId, assembly)
        {
            this.slotDefinitions = slotDefinitions;
        }

        internal override QualificationState InternalQualify()
        {
            var builder = new StringBuilder();

            if (slotDefinitions.Count == 0)
            {
                builder.AppendFormat("\n  {0}", Messages.ContractHasNoSlotDefinitions);
                qualificationState |= QualificationState.None | QualificationState.ContractHasNoSlotDefinitions;
            }

            var status = Runtime.Repository.contracts.Values.
                Any(ci => ci.Name == Name && ci != this && ci.IsQualified);

            if (status)
            {
                builder.AppendFormat("\n  {0}", Messages.ContractAlreadyExists);
                qualificationState |= QualificationState.None | QualificationState.ContractNameAlreadyExists;
            }
            else
                qualificationState &= ~(QualificationState.None | QualificationState.ContractNameAlreadyExists);

            qualificationState &= ~(QualificationState.None | QualificationState.QualificationMissing);

            RuntimeBase.LogQualifyResult(
                this,
                qualificationState,
                unqualifiedState,
                warningState,
                Messages.QualifyContract,
                builder.ToString());

            return qualificationState;
        }

        public override bool IsQualified
        {
            get { return (qualificationState & unqualifiedState) == QualificationState.None; }
        }

        public RepositoryCollection<SlotDefinition> SlotDefinitions
        {
            get { return slotDefinitions; }
        }
    }
}

